<%= javascript_include_tag 'leaflet-blurred-location/dist/Leaflet.BlurredLocation.js' %>
<%= javascript_include_tag('/lib/leaflet-spin/example/spin/dist/spin.min.js') %>
<%= javascript_include_tag('/lib/leaflet-spin/example/leaflet.spin.min.js') %>

<div id="map_content" class="modal-body text-left">
  <div class="row">

    <div class="col-lg-7">

      <div id="map" class="leaflet-map" style="width: 100%; height: 300px; margin-bottom:10px;"></div>
      <div class="slide-container">
        <label><%= translation('locations.form.scale') %></label>
        <input id="ex1" data-slider-id='ex1Slider' type="text" data-slider-min="1" data-slider-max="18" data-slider-step="1" data-slider-value="6" style="width: 100%"/>
        <p class="small-description d-inline"><%= translation('locations.form.world') %></p>
        <p class="small-description d-inline" style="float: right"><%= translation('locations.form.building') %></p>
      </div>

    </div>


    <div class="col-lg-5">

      <div class="form-group">
        <label for="placenameInput"><%= translation('locations.form.search_name') %></label>
        <input id="placenameInput" type="text" class="form-control" />
      </div>

      <div class="form-group">
        <%= translation('locations.form.coordinates') %>

        <div id="coord_input" class="row">
          <div class="col-sm-6">
            <label class="small-description"><%= translation('locations.form.latitude') %></label>
            <input id="lat" type="text" class="form-control" placeholder="<%= translation('locations.form.latitude') %>" />
          </div>

          <div class="col-sm-6">
            <label class="small-description"><%= translation('locations.form.longitude') %></label>
            <input id="lng" type="text" class="form-control" placeholder="<%=translation('locations.form.longitude') %>" />
          </div>
        </div>
      </div>

      <!-- Not part of LBL library -->
      <% if current_user %>
        <div class="form-group recent-locations">
          <% latest_locations = current_user.recent_locations %>
          <% if latest_locations.count > 0 %>
            <label>Your recently used locations:</label>
            <select id="recent_locations" name="recent_locations" class="custom-select custom-select-sm">
              <% latest_locations.reverse.each_with_index do |location, index| %>
                <option value='{ "lat": <%= location.lat %>, "lon": <%= location.lon %> }' >
                    <% if location.place %>
                      <%= location.place %>:
                    <% end %>
                    (<%= location.lat %>, <%= location.lon %>)
                </option>
              <% end %>
            </select>
          <% end %>
        </div>
      <% end %>

      <div class="form-group">
        <button class="btn btn-lg btn-outline-secondary" onclick="blurredLocation.geocodeWithBrowser(true);">
          <div id="ldi-geocode-button">
            <i class="fa fa-compass"></i>
            <%= translation('locations.form.current_location') %>
          </div>
        </button>
      </div>

      <div class="form-check">
        <label class="form-check-label">
          <input id="obscureLocation" type="checkbox" checked class="form-check-input" onchange='blurredLocation.setBlurred(document.getElementById("obscureLocation").checked);' />
          <%= translation('locations.form.blur_location') %>
        </label>
        <span class="small-description"><a href="https://publiclab.org/location-privacy" target="_blank"><%= translation('locations.form.learn_more') %></a></span>
      </div>

    </div>

  </div>
</div>

<div class="modal-footer bg-light">

  <div class="location-box text-left">
    <div id="place_name">
      <input id="placenameDisplay" type="text" class="form-control" data-preventOverwrite="false" />
      <label for="placenameDisplay" class="small-description"><%= translation('locations.form.location_saved')%></label>
    </div>
  </div>

  <div class="button-box">
    <!-- <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> -->
    <button data-dismiss="modal" class="btn btn-lg btn-primary" onclick="saveLocation()"><%= translation('locations.form.save') %></button>
  </div>

</div>

<script>

  var bounds = new L.LatLngBounds(
    new L.LatLng(90, -180),
    new L.LatLng(-90, 180)
  );

  var options = {
    InterfaceOptions: {
      latId: 'lat',
      lngId: 'lng',
      placenameDisplayOnError: ''
    },
    location: {
      lat: 23,
      lon: 77
    }
  };

  var blurredLocation;

  (function() {

    L.Icon.Default.imagePath = '/lib/leaflet/dist/images/';

    <% if current_user %>
      <%  latest_location = current_user.latest_location %>
      <% unless latest_location.nil? %>
        options.location.lat = <%= latest_location.lat %> ;
        options.location.lon = <%= latest_location.lon %> ;
      <% end %>
    <% end %>

    blurredLocation = new BlurredLocation(options);

    blurredLocation.panMapToGeocodedLocation("placenameInput");

    blurredLocation.map.setMaxBounds(bounds);

    var changeZoom = function() {
      var zoom = slider.getValue();
      blurredLocation.map.setZoom(zoom);
    }

    var slider = $('#ex1').slider()
      .on('slide', changeZoom)
      .data('slider');

    blurredLocation.map.on('zoomend', function() {
      let zoom = blurredLocation.map.getZoom();
      $('#ex1').slider('setValue', zoom);
    })

    $('#coord_button').click((event) => {
      event.preventDefault();
      $('#coord_input').toggle();
    });
    $("#coord_input").hide();

    $('#recent_locations').change((event) => {
      let location = JSON.parse($('#recent_locations').val());
      blurredLocation.map.setView([location.lat, location.lon], blurredLocation.getZoomFromCoordinates(location.lat, location.lon));
    });

    var initialPlacename = '';
    $('#placenameDisplay').on('focusin', function() {
      initialPlacename = $('#placenameDisplay').val();
    });
    $('#placenameDisplay').on('focusout', function() {
      if($('#placenameDisplay').val() === '') {
        $('#placenameDisplay').attr('data-preventOverwrite', 'false');
      } else if ($('#placenameDisplay').val() !== initialPlacename) {
        $('#placenameDisplay').attr('data-preventOverwrite', 'true');
      }
    });

  })();
  function saveLocation() {
    var tags = 'lat:' + blurredLocation.getLat() + ',lon:' + blurredLocation.getLon() + ',zoom:' + blurredLocation.getZoom();
    if (blurredLocation.isBlurred()) tags = tags + ',' + 'location:blurred'
    if ($('#placenameDisplay').val() !== ('Location unavailable' || '')) {
      tags = tags + ',' + 'place:' + parameterize($('#placenameDisplay').val());
    }
    <% if params[:url] %>
      addTag(tags, '<%= params[:url] %>', "", locationCallback);
    <% else %>
      addTag(tags, null, "", locationCallback);
    <% end %>
    <% if params[:reload] %>setTimeout(function() { location.reload(); }, 3000);<% end %>
  }

  function locationCallback(event){
    if (event.errors.length > 0 && event.errors.includes("Error: tag already exists.")) {
        notyNotification('relax', 3000, 'error', 'topRight', 'Location Already Saved.');
      } else if (event.saved.length > 0) {
        notyNotification('relax', 3000, 'success', 'topRight', 'Location Saved');
      } else {
        notyNotification('relax', 3000, 'error', 'topRight', 'Something went wrong. Contact administrator.');
    }
  }

  function parameterize(input) {
    return input.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/(^-|-$)/g,'');
  }
</script>
